-- ShopDrawPanel
-- 翻牌抽奖系统

local ShopDrawRender = import(".renders.ShopDrawRender")
local ResRender = require("app.widget.renders.ResRender")
local ListViewVertical = require("app.widget.listview.ListViewVertical")
local NewRareInfoView = require("app.newBag.views.NewRareInfoView")

local ClassRef = app.mvc.createPanelClass(...)

local NEED_BUY_ITEM_STR = L("mountticket_notenough")

function ClassRef.create(node)
    local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.ShopDrawPanel))
    sprite:init()
    return sprite
end

function ClassRef:init(data)
    self.super.init(self, data)
    
    self._model = app:getInst("MallModel")
    -- money
    self._resRender = ResRender.create(self._ui.Panel_money)
    self._resRender:setVisible(true)
    -- 掉落预览btn
    self._ui.btn_see:addClickEventListener(function()
        executeFunc(self._onOperate, "openShopDrawDropView", self._cardId)
    end)
    -- 翻转一次
    self._onceDrawNode = self._ui["Panel/Panel_bom/Panel_up"]
    self._onceDrawNode:getChildByName("Button"):addClickEventListener(function()
        if self._cardId then
            local needNum = self._costOnceData:getAmount()
            if self._info.freeTimes <= 0 and self._moneyInfo and self._moneyInfo.num < needNum then
                local str = string.format(NEED_BUY_ITEM_STR, self._costOnceData:getName())
                executeFunc(self._onOperate, "needBuy", str, self._costOnceData:getId())
            else
                if self._info.isFinished then
                    local creataeTeamDialog = display.newConfirmDialog( L(self._conf.finishSring),
                    function(sender) -- 确定
                        executeFunc(self._onOperate, "shopDrawCard", {id = self._cardId, type = 1})
                    end)
                    UIHandler:addPopDialog( creataeTeamDialog )
                else
                    executeFunc(self._onOperate, "shopDrawCard", {id = self._cardId, type = 1})
                end
            end
        end
    end)
    -- 翻转十次
    self._moreDrawNode = self._ui["Panel/Panel_bom/Panel_10"]
    self._moreDrawNode:getChildByName("Button"):addClickEventListener(function()
        if self._cardId then
            local needNum = self._costTenData:getAmount()
            if self._moneyInfo and self._moneyInfo.num < needNum then
                local str = string.format(NEED_BUY_ITEM_STR, self._costTenData:getName())
                executeFunc(self._onOperate, "needBuy", str, self._costTenData:getId())
            else
                if self._info.isFinished then
                    local creataeTeamDialog = display.newConfirmDialog( L(self._conf.finishSring),
                    function(sender) -- 确定
                        executeFunc(self._onOperate, "shopDrawCard", {id = self._cardId, type = 2})
                    end)
                    UIHandler:addPopDialog( creataeTeamDialog )
                else
                    executeFunc(self._onOperate, "shopDrawCard", {id = self._cardId, type = 2})
                end
            end
        end
    end)
    -- tipsBtn
    self._ui.Button_explain:addClickEventListener(function()
        self:showProbabilityTips()
    end)
    -- left ListView
    self:initListView()

    -- timeline
    self._timeline = self._ui.card:getTimeline()
    if self._timeline then
        self._timeline:gotoFrameAndPause(0)
    end
end

function ClassRef:initListView()
     local params = {
		renderClass = ShopDrawRender,
		perNum = 1,
		cellEventProxy = function(eventName, cellModel)
            if eventName == "click" then
                self:onChangeSelectCard(cellModel:getIndex())
            end
		end,
	}
    self._listview = ListViewVertical.new( self._ui["Panel/ScrollView"], params )
end

function ClassRef:reloadData(data, params)
    if not data then
        data = self._model:getShopDrawInfo()
    end
    self._listData = data
    self._listview:reloadData(data, params )
end

function ClassRef:refreshShopDraw(index)
    self:reloadData()
    self:onChangeSelectCard(index)
end

function ClassRef:onChangeSelectCard(index)
    if not self._listData then
        return
    end
    executeFunc(self._onOperate, "switchShopDraw", index) -- 修改选中的卡池
    self._listview:setFoucsIndex(index)
    self:_updateCardInfo()
    self:updateMoneyInfo(index)
end

function ClassRef:_updateCardInfo()
    local cardInfo = self:getCurSelectCard()
    if not cardInfo then
        return
    end
    self._cardId = cardInfo.info.id
    self._conf = cardInfo.config
    self._info = cardInfo.info
    -- centerInfo
    self._ui["Panel/Panel_card/tlt"]:setString(L(self._conf.titleName))
    self._ui["Panel/Panel_card/tips"]:setString(L(self._conf.menuTips1))
    local cardNode = self._ui["Panel/Panel_card/card"]
    local iconPath = string.format("%s%s.png",Res.activityIconPath,self._conf.cardIcon)
    cardNode:findChild("Panel/img_back"):loadTexture(iconPath)
    self._timeline:play( "float", true ) -- 循环播放抖动动画
    -- bottom
    local bottomNode = self._ui["Panel/Panel_bom"]
    local percent = math.floor(self._info.probability/100)
    bottomNode:getChildByName("tlt"):setString(string.format(L("activityCardTips1"), percent)) 
    bottomNode:findChild("bar/LoadingBar"):setPercent(percent)
    -- 翻转一次按钮
    local onceBtn = bottomNode:getChildByName("Panel_up")
    self:setShopDrawButton(onceBtn, 1)
    -- 翻转十次按钮
    local tenBtn = bottomNode:getChildByName("Panel_10")
    self:setShopDrawButton(tenBtn, 2)
end

function ClassRef:getCurSelectCard()
    if not self._listData then
        return
    end
    local focusIndex = self._listview:getFoucsIndex()
    local info = self._listData[focusIndex]
    return info
end

function ClassRef:updateMoneyInfo(index)
    if self._resRender then
        self._moneyInfo = self._model:getShopDrawMoneyInfo(index)
        if self._moneyInfo then
            self._resRender:setData(self._moneyInfo)
            if self._conf then
                local iconPath = string.format("%s%s.png",Res.itemPath,self._conf.coinIcon)
                self._resRender:setIcon(iconPath)
            end
        end
    end
end

function ClassRef:onOperate(cb)
	self._onOperate = cb
end

function ClassRef:showProbabilityTips()
    local dataTemp = {
		name=L("lua_code_text_440"),
		string1 = L(self._conf.menuTips2),
	}

	if self.eventTips then
		self.eventTips:setData( dataTemp )
	else
		self.eventTips = NewRareInfoView.create()
		self.eventTips:setData( dataTemp )
		self:addChild( self.eventTips )

		local triggerNodeBoundingBox = self._ui.Button_explain:getBoundingBox()
		local worldPosTemp = self._ui.Button_explain:getParent():convertToWorldSpace( cc.p( triggerNodeBoundingBox.x, triggerNodeBoundingBox.y ) )
		triggerNodeBoundingBox.x = worldPosTemp.x
		triggerNodeBoundingBox.y = worldPosTemp.y
		display.adjustNodePos( triggerNodeBoundingBox, self.eventTips , -66, 5)

		-- 点击空白区域关闭
		display.nodeRemoveForNotHit(self.eventTips, function()
			if self.eventTips then
				self.eventTips:removeFromParent()
				self.eventTips = nil
			end
		end)
	end
end

function ClassRef:setShopDrawButton(node, type)
    local btnNode = node
    local costStr
    if type == 1 then
        costStr = self._conf.cost
        self._costOnceData = UD:parseRewardToBagItem(costStr)
    else
        costStr = self._conf.tenCost
        self._costTenData = UD:parseRewardToBagItem(costStr)
    end
    local costData = UD:parseRewardToBagItem(costStr)
    btnNode:getChildByName("num"):setString( tostring(costData:getAmount()) )
    local iconPath = string.format("%s%s.png",Res.itemPath,self._conf.coinIcon)
    btnNode:getChildByName("icon"):loadTexture(iconPath)--(costData:getIcon())
    if btnNode:getChildByName("dot") then
        btnNode:getChildByName("dot"):setVisible(false)
    end
    if type == 1 and self._info.freeTimes > 0 and btnNode:getChildByName("dot") then
        btnNode:getChildByName("num"):setString(0)
        btnNode:getChildByName("dot"):setVisible(true)
        btnNode:findChild("dot/num_2"):setString(self._info.freeTimes)
    end
end

return ClassRef